package cn.youyeku.zsxh.ui.home;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import cn.youyeku.zsxh.R;
import cn.youyeku.zsxh.Utils.AppConfig;
import cn.youyeku.zsxh.Utils.CircleImageView;
import cn.youyeku.zsxh.Utils.DialogUtils;
import cn.youyeku.zsxh.Utils.ImageUtils;
import cn.youyeku.zsxh.Utils.StringUtils;
import cn.youyeku.zsxh.api.XhApi;
import cn.youyeku.zsxh.app;
import cn.youyeku.zsxh.bean.User;
import cn.youyeku.zsxh.ui.UIControl;
import cn.youyeku.zsxh.ui.activity.ABS.FeedbackActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static cn.youyeku.zsxh.Utils.AppConfig.CONF_USER_BIRTHDAY;
import static cn.youyeku.zsxh.Utils.AppConfig.CONF_USER_SEX;
import static cn.youyeku.zsxh.Utils.AppConfig.CONF_USER_SIGN;

/**
 * Created by youye on 17-4-11.
 */

public class UserProfile extends FeedbackActivity implements View.OnClickListener {

    private CircleImageView profile_img;
    private RelativeLayout profile_layout_img;
    private TextView profile_nickname;
    private RelativeLayout profile_layout_nickname;
    private TextView profile_sex;
    private RelativeLayout profile_layout_sex;
    private TextView profile_birthday;
    private RelativeLayout profile_layout_birthday;
    private TextView profile_sign;
    private RelativeLayout profile_layout_sign;
    private Button profile_modify;
    private Button profile_logout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_user_profile);
        initView();




    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.profile_layout_img:
                setImg();
                break;

            case R.id.profile_layout_nickname:
//                setNickName();
                break;

            case R.id.profile_layout_sex:
                setSex();
                break;

            case R.id.profile_layout_birthday:
                setBirthday();
                break;

            case R.id.profile_layout_sign:
                setSign();
                break;
            case R.id.profile_modify:
                modify();
                break;
            case R.id.profile_logout:
                login_out();

                break;
        }
    }

    private void login_out() {
        new MaterialDialog.Builder(this)
                .title("要注销？？")
                .content("确定注销")
                .positiveText("注销")
                .negativeText("手滑了~~").callback(new MaterialDialog.ButtonCallback() {
            @Override
            public void onPositive(MaterialDialog dialog) {
                super.onPositive(dialog);
                XhApi.login_out(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        AppConfig.LoginOut();
                        UIControl.showLogin(getApplicationContext());
                    }
                });
            }

            @Override
            public void onNegative(MaterialDialog dialog) {
                super.onNegative(dialog);
            }
        })
                .show();

    }

    private void modify() {
        XhApi.update_profile(profile_sign.getText().toString(), profile_birthday.getText().toString(),
                profile_sex.getText().toString().equals("男")?"1":"2", local_file_path,new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        try {
                            String data = response.body().string();

                            JSONObject object = new JSONObject(data);
                            Gson gson = new Gson();
                            User user = gson.fromJson(object.getString("data"), User.class);

                            int code = object.getInt("code");

                            if (code == 200) {
                                CONF_USER_SEX = user.getSex();
                                CONF_USER_SIGN = user.getSign();
                                CONF_USER_BIRTHDAY = user.getBirthday();
                                Properties ps = AppConfig.getProps();
                                ps.setProperty("CONF_USER_SEX", CONF_USER_SEX);
                                ps.setProperty("CONF_USER_SIGN", CONF_USER_SIGN);
                                ps.setProperty("CONF_USER_BIRTHDAY", CONF_USER_BIRTHDAY);
                                AppConfig.set(ps);
                            }

                            app.backgroundThreadShortToast(object.getString("message"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });

    }




    private void setSign() {
        DialogUtils.changeTextView(this,profile_sign,"个性签名");
    }

    private void setBirthday() {
        Calendar c = null;
        c = Calendar.getInstance();
        new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker dp, int year, int month, int dayOfMonth) {
                profile_birthday.setText(year + "-" + month + "-" + dayOfMonth);
            }
        }, c.get(Calendar.YEAR), // 传入年份
                c.get(Calendar.MONTH), // 传入月份
                c.get(Calendar.DAY_OF_MONTH) // 传入天数
        ).show();
    }

    private void setSex() {
        final String[] sex = {"♂男", "♀女"};
        new MaterialDialog.Builder(this)
                .title("选择")
                .items(sex)
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                        profile_sex.setText(text);
                    }
                }).show();
    }

    private void setNickName() {
        new MaterialDialog.Builder(this)
                .title("输入昵称")
                .inputType(InputType.TYPE_CLASS_TEXT)
                //参数1：hint 参数2：自动填充的文字 参数3：监听
                .input(null, null, new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(MaterialDialog dialog, CharSequence input) {
                        profile_nickname.setText(input);
                    }
                }).show();

    }

    private  void setImg() {
        String[] array = {"图库", "拍照"};
        new MaterialDialog.Builder(this)
                .title("选择")
                .items(array)
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
//                        Log.d("position是：", "" + position);
                        if (position == 0) {//图库
                            pickFromGallery();

                        } else if (position == 1) {//相机
                            pickFromCamera();
                        }
                    }
                }).show();
    }

    public void pickFromGallery() {

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, GALLERY_REQUEST_CODE);
    }

    public void pickFromCamera() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(getExternalCacheDir(), IMAGE_FILE_NAME)));
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }

    private void initView() {
        profile_img = (CircleImageView) findViewById(R.id.profile_img);

        profile_layout_img = (RelativeLayout) findViewById(R.id.profile_layout_img);
        profile_layout_img.setOnClickListener(this);
        profile_nickname = (TextView) findViewById(R.id.profile_nickname);

        profile_layout_nickname = (RelativeLayout) findViewById(R.id.profile_layout_nickname);
        profile_layout_nickname.setOnClickListener(this);
        profile_sex = (TextView) findViewById(R.id.profile_sex);

        profile_layout_sex = (RelativeLayout) findViewById(R.id.profile_layout_sex);
        profile_layout_sex.setOnClickListener(this);
        profile_birthday = (TextView) findViewById(R.id.profile_birthday);

        profile_layout_birthday = (RelativeLayout) findViewById(R.id.profile_layout_birthday);
        profile_layout_birthday.setOnClickListener(this);
        profile_sign = (TextView) findViewById(R.id.profile_sign);

        profile_layout_sign = (RelativeLayout) findViewById(R.id.profile_layout_sign);
        profile_layout_sign.setOnClickListener(this);



        profile_modify = (Button) findViewById(R.id.profile_modify);
        profile_modify.setOnClickListener(this);
        profile_logout = (Button) findViewById(R.id.profile_logout);
        profile_logout.setOnClickListener(this);




        profile_birthday.setText(AppConfig.CONF_USER_BIRTHDAY.replace(" 00:00:00",""));
        profile_sex.setText(AppConfig.CONF_USER_SEX.equals("1")?"男":"女");
        profile_nickname.setText(AppConfig.CONF_USER_NICK_NAME);
        profile_sign.setText(AppConfig.CONF_USER_SIGN);
        ImageUtils.GlideCircleImg(getApplicationContext(),profile_img,XhApi.getFace(AppConfig.CONF_USER_ID));
    }

    @Override
    protected void setPicturePreview(Uri resultUri) {
        Glide.with(getApplicationContext())
                .load(resultUri)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .error(R.drawable.default_avatar)
                .into(profile_img);
    }
}
